<?php
namespace App\Http\Controllers\Index;

use App\Http\Controllers\Controller;
use App\Logic\Code;
use App\Logic\finger\MinerBalanceLogic;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Logic\finger\MinerLogic;
use Illuminate\Support\Facades\Validator;


class MinerBalanceController extends Controller
{
    /**
     *  收益详情，收益记录,划转
     */



    /**
     * @OA\Post(
     *     path="/miner_balance_xq",
     *     tags={"矿机钱包"},
     *     summary="详情",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"mid","token"},
     *                 @OA\Property(property="mid", type="number", description="矿机id"),
     *                 @OA\Property(property="token", type="string", description="币种类型"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="total总，already已提现，rel剩余",
     *     )
     * )
     */
    public function xq(Request $request)
    {
        $data = $request->all();
        return MinerBalanceLogic::xq($data);

    }


    /**
     * @OA\Post(
     *     path="/admin/minerBalanceProfit",
     *     tags={"矿机钱包"},
     *     summary="记录",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="mid", type="number", description="矿机id搜索"),
     *                 @OA\Property(property="m_number", type="string", description="矿机编号搜索"),
     *                 @OA\Property(property="token", type="string", description="矿机token搜索 FIL ETH"),
     *                 @OA\Property(property="type", type="string", description="矿机类型搜索"),
     *                 @OA\Property(property="key", type="string", description="键为 username,phone"),
     *                 @OA\Property(property="val", type="string", description="值"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function profit(Request $request)
    {
        $post_data = $request->all();

        $where = [];
        if($request->has('limit')){
            $limit = $request->input('limit');
        }else{
            $limit = 15;
        }
        if(isset($post_data['mid'])){
            $where[] = ['mb.mid','=',$request->input('mid')];
        }
        if(isset($post_data['m_number'])){
            $where[] = ['mi.m_number','=',$request->input('m_number')];
        }
        if(isset($post_data['token'])){
            $where[] = ['mb.token','=',$request->input('token')];
        }
        if(isset($post_data['type'])){
            $where[] = ['mb.type','=',$request->input('type')];
        }

        if(isset($post_data['key']) && isset($post_data['val'])){

            if(!in_array($post_data['key'],['phone','username'])){
                return e_msg(123456,'只能搜索phone,username');
            }
            $key = 'u.'.$post_data['key'];
            $where[] = [$key,'=',$post_data['val']];
        }

        if(isset($this->user['id'])){
            $where[] = ['u.username','=',$this->user['username']];
        }

        $miner_list = Db::table('miner_balance as mb')
            ->join('miner_info as mi','mi.mid','=','mb.mid')
            ->join('miner_host as mh','mh.mid','=','mb.mid')
            ->join('miner_user as mu','mu.mid','=','mb.mid')
            ->join('user as u','u.username','=','mu.user_name')
            ->where($where)
            ->orderBy('mb.timestamp','desc')
            ->select('mb.*','mh.hspace','mi.m_number','mu.user_name','u.phone')
            ->paginate($limit);
        //保留6位小数
        foreach ($miner_list as $value){
            $value->amount = number_format($value->amount , 6) ;
        }
        return s_msg('',$miner_list);

    }


    /**
     * @OA\Post(
     *     path="/miner_balance_transfer",
     *     tags={"矿机钱包"},
     *     summary="划转",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="mid", type="number", description="矿机id"),
     *                 @OA\Property(property="code", type="string", description="短信验证码"),
     *                 @OA\Property(property="amount", type="string", description="划转数量"),
     *                 @OA\Property(property="token", type="string", description="划转币种  ETH"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function transfer(Request $request)
    {
        $post_data = $request->all();

        $scene = $request->path();
        return MinerBalanceLogic::transfer($post_data,$this->user,$scene);
        $validateRule = [
            'amount' => 'required',
            'code' => 'required',
            'mid' => 'required',
            'token' => 'required',
        ];
        $errorMsg = [
            'mid.required' => '请传入矿机信息',
            'amount.required' => '请传入划转数量',
            'code.required' => '请传入验证码',
            'token.required' => '请传入币种信息',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }


        $scene = $request->path();
        $key = $this->user['phone'] . '_code_' . $scene;

        $code_info = Code::code($key, $post_data['code']);
        if ($code_info['status'] === 'ERROR') {
            return $code_info;
        }

        if($post_data['token'] != 'ETH'){
            return e_msg(123456,'只有ETH才能划转');
        }
        $miner_user_id = DB::table('miner_user')
            ->where('mid',$post_data['mid'])
//            ->where('user_name',$this->user['username'])->first();
            ->value('id');

        if(!$miner_user_id){
            return e_msg(300001,'该矿机不是您的');
        }

        $rel_amount = DB::table('miner_balance')
            ->where('token', $post_data['token'])
            ->where('mid', $post_data['mid'])
            ->sum('amount');

        $time = time();

        $power = DB::table('miner_host')
            ->where('mid',$post_data['mid'])
            ->where('add_time','<',$time)
            ->where('end_time','>',$time)
            ->value('hspace');

        if($power){

            $day_mining_num = Cache::get('configs')['eth']['day_mining_num']->val;
            $block_time = Cache::get('configs')['eth']['block_time']->val;
            $eth_today = get_etc_today_num($power,$day_mining_num,$block_time);

        }else{
            $eth_today = 0;
        }

        if ($rel_amount+$eth_today < $post_data['amount']) {
            return e_msg(300026, '划转余额不足');
        }


        $fee = $post_data['amount'] * Cache::get('configs')['eth']['transfer_fee']->val;

        if ($this->user['rebate'] < $fee) {
            return e_msg(300029, 'srt积分不足');
        }

        $address = DB::table("miner_wallet")
            ->where('user_name', $this->user['username'])
            ->where('token', $post_data['token'])
            ->value('address');

        if (!$address) {
            return e_msg(300027, '请先绑定钱包地址');
        }

        $balance_insert_arr = [
            'token' => $post_data['token'],
            'mid' => $post_data['mid'],
            'amount' => '-'.$post_data['amount'],
            'ticket' => 'data_transfer_' . date('YmdHis'),
            'type' => 'eth_transfer',
            'type_note' => '转出',
        ];

        $eth_insert_arr = [
            'out_account' => $this->user['username'],
            'out_phone' => $this->user['phone'],
            'shift_account' => '自己',
            'shift_phone' => '自己',
            'amount' => $post_data['amount'],
            'type_note' => '矿机资金划转',
            'type' => 'eth_miner_transfer',
        ];

        $srt_insert_arr = [
            'out_account' => $this->user['username'],
            'out_phone' => $this->user['phone'],
            'shift_account' => '自己',
            'shift_phone' => '自己',
            'amount' => -$fee,
            'type_note' => '手续费',
            'type' => 'eth_transfer_fee',
        ];

        //用户表添加eth，矿机钱包表记录，eth表记录，srt表记录，用户表扣除srt
        //提现审核表，收益记录表
        DB::beginTransaction();
        $rel1 = DB::table('user')->where('id',$this->user['id'])->increment('eth',$post_data['amount']);
        $rel2 = DB::table('miner_balance')->insert($balance_insert_arr);
        $rel3 = DB::table('record_eth')->insert($eth_insert_arr);
        $rel4 = DB::table('record_srt')->insert($srt_insert_arr);
        $rel5 = DB::table('user')->where('username',$this->user['username'])->decrement('rebate',$fee);
        if($rel1&&$rel2&&$rel3&&$rel4&&$rel5){
            DB::commit();
            return s_msg('');
        }else{
            DB::rollBack();
            return e_msg(123456,'有问题');
        }

    }
     //脚本的数据
    public function add_profit(){
        $dataTime = date('Y-m-d', time());
        if($dataTime >= '2020-05-19'){
            self::addBalanceTime( date('Y-m-d 23:59:59', strtotime("-1 day"))) ;
        }else{
            $dataTime = array(
                "2020-05-15 23:59:59" ,
                "2020-05-16 23:59:59" ,
                "2020-05-17 23:59:59" ,
            );
            for ($j = 0 ; $j<count($dataTime) ; $j++){
                self::addBalanceTime($dataTime[$j]) ;
            }
        }


        return s_msg('',"ok");
    }
    public function  addBalanceTime($dataTime){
        $userMinerCount = DB::table("miner_host as mh")
            ->join('miner_user as mu',"mh.mid" ,"=","mu.mid")
            ->select('mh.hspace' ,'mh.token' , 'mh.mid')
            ->count();
        $limit = 10 ;
        for($i = 0 ; $i <ceil($userMinerCount/$limit); $i++){
            $office = $i*$limit;

            $userMiner = DB::table("miner_host as mh")
                ->join('miner_user as mu',"mh.mid" ,"=","mu.mid")
                ->select('mh.hspace' ,'mh.token' , 'mh.mid')
                ->offset($office)
                ->limit($limit)
                ->get() ;

            foreach ($userMiner as $value){
                $data = array(
                    "mid" => $value->mid ,
                    "token" => $value->token ,
                    "amount" => $value->hspace *0.9,
                    "type" => "mining",
                    'ticket' => '挖矿',
                    'type_note' =>'挖矿',
                    'timestamp' => $dataTime
                ) ;
                DB::table('miner_balance')->insert($data);
            }
        }
    }
}
